<template>
    <div>
      <el-card class="member-box-card">
      <div class="block">
        <span class="demonstration">时间选择 </span>
        <el-date-picker
          v-model="value2"
          value-format="yyyyMMddHHmmss"
          @change="handleDate(value2)"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right">
        </el-date-picker>
      </div>
      <el-table id="member-table" :key="itemKey" v-loading="loading" :data="tableData" height="250"
                border style="width: 100%" max-height="450">
        <el-table-column prop="id" label="序号" />
        <el-table-column prop="name" label="货物名称" />
        <el-table-column prop="specification" label="型号规格" />
        <el-table-column prop="unit" label="计量单位" />
        <el-table-column prop="position" label="存放位置" />
        <el-table-column prop="price" label="单价" />
        <el-table-column prop="entryNum" label="入库数量" />
        <el-table-column prop="entryDate" label="入库日期" />
        <el-table-column prop="keeper" label="材料管理员" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column align="right">
          <template slot="header" slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="setExport2Excel"
            >导出</el-button>
          </template>
        </el-table-column>
      </el-table>
      </el-card>
    </div>
</template>

<script>
  import {selectAllentry, selectBetweenDate} from '@/api/entrywarehouse/entry-form'
  import { getToken } from '@/utils/auth'
  import XLSX2 from "xlsx";
  import XLSX from "xlsx-style";
  import FileSaver from 'file-saver';

  export default {
    name: 'index',
    data() {
      return {
        tableData: [],
        itemKey: '',
        loading: false,
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        value2: '',
        headers: {
          Authorization: getToken()
        }
      };
    },
    created() {
      this.init()
    },
    methods: {
      init() {
        selectAllentry().then((response) => {
          this.tableData = response.data
        })
      },
      handleDate(value2){
        console.log(value2)
        //this.loading = true
        selectBetweenDate(value2[0],value2[1]).then((response) =>{
            this.tableData = response.data
            this.loading = false
            this.itemKey = Math.random()
        })
      },

      setExport2Excel() {
        require.ensure([], () => {
            const { export_json_to_excel} = require("@/excelentry/export2Excel")
            const title = [
              "检测中心材料入库登记表","","","","","","","","",""
            ]
            const date = [
              "          年        月         日                                                                                                                      负责人：","","","","","","","","",""
            ]
            const merges1 = [
              "A1:J1",
              "A2:J2"
            ]
            const tHeader = [
              "序号",
              //"流水号",
              "货物名称",
              "型号规格",
              "计量单位",
              "存放位置",
              "单价",
              "入库数量",
              "入库日期",
              "材料管理员",
              "备注"
            ] // 上面设置Excel的表格第一行的标题
            const filterVal = [
              "id",
              "name",
              "specification",
              "unit",
              "position",
              "price",
              "entryNum",
              "entryDate",
              "keeper",
              "remark"
            ]

            let list = this.tableData //把要导出的数据tableData存到list   这个数组不能为空

            for (let i= 0; i < list.length; i++){
                 if (list[i].keeper == null ){
                   list[i].keeper = " "
                 }
                 if (list[i].remark == null){
                   list[i].remark = " "
                 }
            }
            const data1 = this.formatJson(filterVal, list)

             export_json_to_excel(title,date,tHeader, data1, "入库登记表",merges1)
          }).catch((err) => {
            console.log("导出失败");
          })
      },

      //格式转换,不需要改动
      formatJson(filterVal, jsonData) {
        //console.log(jsonData);
        return jsonData.map((v) => filterVal.map((j) => v[j]));
      },




      // setExport2Excel() {
      //   /* generate workbook object from table */
      //   var xlsxParam = { raw: true }
      //   var wb = XLSX2.utils.table_to_sheet(document.querySelector("#member-table"), xlsxParam);//mytable为表格的id名
      //   if(!wb['!merges']){
      //     this.$message.warning('无法导出：报表无数据');
      //     return
      //   }
      //   for(var i = 0;i<11;i++){
      //     wb["!cols"][i]={wpx:150}
      //   }
      //   // 样式的文档地址
      //   // https://www.npmjs.com/package/xlsx-style
      //   for (const key in wb) {
      //     if(key.indexOf('!') === -1&&wb[key].v){
      //       wb[key].s ={
      //         font:{//字体设置
      //           sz:13,
      //           bold:false,
      //           color:{
      //             rgb:'000000'//十六进制，不带#
      //           }
      //         },
      //         alignment:{//文字居中
      //           horizontal:'center',
      //           vertical:'center',
      //           wrap_text:true
      //         },
      //         border: { // 设置边框
      //           top: { style: 'thin' },
      //           bottom: { style: 'thin' },
      //           left: { style: 'thin' },
      //           right: { style: 'thin' }
      //         }
      //       }
      //     }
      //   }
      //   var data = this.addRangeBorder(wb['!merges'],wb) //合并项添加边框
      //   var filedata = this.sheet2blob(data)
      //   this.openDownloadDialog(filedata,this.todayTimeString + "入库登记报表.xlsx")
      // },
      //为合并项添加边框
      addRangeBorder(range,ws){
        let arr = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];

        range.forEach(item=>{
          let startColNumber = Number(item.s.r), endColNumber = Number(item.e.r);
          let startRowNumber = Number(item.s.c), endRowNumber = Number(item.e.c);
          const test = ws[arr[startRowNumber] + (startColNumber + 1)];
          for(let col = startColNumber ; col <= endColNumber ; col++)
          {
            for(let row = startRowNumber; row <= endRowNumber ; row++)
            {
              ws[arr[row] + (col + 1)] = test;
            }
          }
        })
        return ws;
      },
      //将一个sheet转成最终的excel文件的blob对象，然后利用URL.createObjectURL下载
      sheet2blob(sheet, sheetName) {
        sheetName = sheetName || 'sheet1';
        var workbook = {
          SheetNames: [sheetName],
          Sheets: {}
        };
        workbook.Sheets[sheetName] = sheet; // 生成excel的配置项

        var wopts = {
          bookType: 'xlsx', // 要生成的文件类型
          bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
          type: 'binary'
        };
        var wbout = XLSX.write(workbook, wopts);
        var blob = new Blob([s2ab(wbout)], {
          type: "application/octet-stream"
        }); // 字符串转ArrayBuffer
        function s2ab(s) {
          var buf = new ArrayBuffer(s.length);
          var view = new Uint8Array(buf);
          for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
          return buf;
        }
        return blob;
      },
      openDownloadDialog(url, saveName) {
        if (typeof url == 'object' && url instanceof Blob) {
          url = URL.createObjectURL(url); // 创建blob地址
        }
        var aLink = document.createElement('a');
        aLink.href = url;
        aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
        var event;
        if (window.MouseEvent) event = new MouseEvent('click');
        else {
          event = document.createEvent('MouseEvents');
          event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        }
        aLink.dispatchEvent(event);
      }

    }


  }
</script>

<style scoped>
  .member-box-card {
    width: 95%;
    margin: 20px auto;
  }
  #member-table {
    margin-top: 5px;
  }

</style>
